const Storage = {
  set (key, value, expires) {
    // let data = value
    // if (typeof value === 'object' && value) {
    //   data = JSON.stringify(value)
    // }
    // localStorage.setItem(key, JSON.stringify(value))
    let params = { key, value, expires }
    if (expires) {
      var data = Object.assign(params, { startTime: new Date().getTime() })
      localStorage.setItem(key, JSON.stringify(data))
    } else {
      if (Object.prototype.toString.call(value) === '[object Object]') {
        value = JSON.stringify(value)
      }
      if (Object.prototype.toString.call(value) === '[object Array]') {
        value = JSON.stringify(value)
      }
      localStorage.setItem(key, value)
    }
  },
  get (key) {
    // let data = localStorage.getItem(key)
    // if (data && data !== 'undefined') {
    //   return JSON.parse(data)
    // } else {
    //   return null
    // }
    let item = localStorage.getItem(key)
    // 先将拿到的试着进行json转为对象的形式
    try {
      item = JSON.parse(item)
    } catch (error) {
      // eslint-disable-next-line no-self-assign
      item = item
    }
    // 如果有startTime的值，说明设置了失效时间
    if (item && item.startTime) {
      let date = new Date().getTime()
      // 如果大于就是过期了，如果小于或等于就还没过期
      if (date - item.startTime > item.expires) {
        localStorage.removeItem(name)
        return false
      } else {
        return item.value
      }
    } else {
      return item
    }
  },
  remove (key) {
    localStorage.removeItem(key)
  },
  setAccessToken (data) {
    console.log('// ---- SessionStorage SetAccessToken:', data)
    sessionStorage.setItem('accessToken', JSON.stringify(data))
  },
  // localStorage
  dispatchLocalStorageEvent () {
    const signSetItem = localStorage.setItem
    localStorage.setItem = function (key, val) {
      let setEvent = new Event('setLocalItemEvent')
      setEvent.key = key
      setEvent.newValue = val
      window.dispatchEvent(setEvent)
      signSetItem.apply(this, arguments)
    }
  },
  // sessionStorage
  dispatchSessionStorageEvent () {
    const signSetItem = sessionStorage.setItem
    sessionStorage.setItem = function (key, val) {
      let setEvent = new Event('setSessionItemEvent')
      setEvent.key = key
      setEvent.newValue = val
      window.dispatchEvent(setEvent)
      signSetItem.apply(this, arguments)
    }
  }
}
export default Storage
